package com.yzy.yzy_crm.shiro;

import com.yzy.yzy_crm.entity.Permission;
import com.yzy.yzy_crm.entity.Role;
import com.yzy.yzy_crm.entity.User;
import com.yzy.yzy_crm.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*权限*/
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        for (Role role : user.getRoleList()) {
            simpleAuthorizationInfo.addRole(role.getRoleName());
            for (Permission permission : role.getPermissionList()) {
                simpleAuthorizationInfo.addStringPermission(permission.getUrl());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*String username = (String) authenticationToken.getPrincipal();
        String password = new String((char [])authenticationToken.getCredentials());*/
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        User user = userMapper.selectUserByName(token.getUsername());
        if (user==null){
            return null;
        }
        /*if (!(user.getUserName().equals(username))){
            throw new UnknownAccountException("用户不存在");
        }
        if (!(user.getPassword().equals(password))){
            throw new IncorrectCredentialsException("密码错误");
        }*/
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),getName());
        return info;
    }
}
